package es.battleship.dao;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import es.battleship.api.dao.PlayerPairDao;
import es.battleship.model.Game;
import es.battleship.model.GameConfig;
import es.battleship.model.PlayerPair;

@Repository
public class PlayerPairDaoImpl implements PlayerPairDao {
	Logger  logger = Logger.getLogger(PlayerPairDaoImpl.class.getName());
	
	private PersistenceManagerFactory persistenceManagerFactory; 

	@Autowired
	public void setPersistenceManagerFactory(
			PersistenceManagerFactory persistenceManagerFactory) {
		this.persistenceManagerFactory = persistenceManagerFactory;
	}

	@Override
	public PlayerPair find(Long id) {
		PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
		
		try {
			Key k = KeyFactory.createKey(PlayerPair.class.getSimpleName(), id);
			
			PlayerPair pair = persistenceManager.getObjectById(PlayerPair.class,k); 
			
			logger.info("find: " + pair);
			
			
			return pair;
		} finally {
			persistenceManager.close();
		}
	}

	@Override
	public List<PlayerPair> findByUser(String user)   {
		PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();

		Query query = persistenceManager.newQuery(PlayerPair.class);
	    query.setFilter("(user1 == name )");
	    query.declareParameters("String name");
	    
		try {
		    List<PlayerPair> results = (List<PlayerPair>) query.execute(user);

		    for (PlayerPair pair :results ) {
		    	logger.info(" " + pair );
		    	
		    	Game g = pair.getGame();
		    	
		    	if (g != null) 
		    	{
		    		GameConfig c  = g.getGameConfig();
		    		
		    		if ( c != null ) {
		    			
		    			c.getShipConfigs();
		    		}
		    	}
		    	
		    }
		    return results;
		    
		} finally {
			query.closeAll();
			persistenceManager.close();
		}
	}

	@Override
	public PlayerPair create(PlayerPair playerPair) {
		PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
		try {
			return persistenceManager.makePersistent(playerPair);
			
		} finally {
			persistenceManager.close();
		}
	}
}
